import { useEffect, useState, useRef } from "react";

const isFalsy = (value: unknown) => (value === 0 ? true : !value);
const isVoid = (value: unknown) =>
  value === null || value === undefined || value === "";
export const cleanObj = (obj?: { [key: string]: unknown }) => {
  const newObj = JSON.parse(JSON.stringify(obj));
  Object.keys(newObj).forEach((key) => {
    const value = newObj[key];
    //如果value是空的 就删除该key
    if (isVoid(value)) {
      delete newObj[key];
    }
  });
  return newObj;
};
//自定义hook
export const useMount = (callBack: () => void) => {
  useEffect(() => {
    callBack();
  }, []);
};
//防抖
export const useDebounce = <V>(value: V, delay: number) => {
  const [debouncedValue, setDebouncedValue] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debouncedValue;
};
// 数组封装
export const useArray = <T>(initArray: T[]) => {
  const [value, setValue] = useState(initArray);
  return {
    value,
    setValue,
    add: (item: T) => setValue([...value, item]),
    clear: () => setValue([]),
    removeItem: (index: number) => {
      const copy = [...value];
      copy.splice(index, 1);
      setValue(copy);
    },
  };
};
export const useDocumentTitle = (
  title: string,
  keepOnUnMount: boolean = true
) => {
  const oldTitle = useRef(document.title).current;
  useEffect(() => {
    document.title = title;
  }, [title]);
  useEffect(() => {
    return () => {
      console.log(
        "33333",
        "document.title",
        document.title,
        "oldTitle",
        oldTitle
      );
      if (!keepOnUnMount) {
        document.title = oldTitle;
        console.log("document.title", document.title);
      }
    };
  }, [keepOnUnMount, oldTitle]);
};
